package com.example.jmeterTest.service.impl;

import com.example.jmeterTest.entity.User;
import com.example.jmeterTest.mapper.UserMapper;
import com.example.jmeterTest.service.UserService;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;

import java.time.LocalDateTime;

@Service
public class UserServiceImpl implements UserService {
    
    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    private static final String USER_CACHE_KEY_PREFIX = "user:id:";
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private RedissonClient redissonClient;
    
    @Override
    public Mono<User> addUser(User user) {
        return Mono.fromCallable(() -> {
            if (user == null) {
                logger.error("Attempting to add null user");
                throw new IllegalArgumentException("User cannot be null");
            }
            
            try {
                // 设置创建时间和更新时间
                user.setCreateTime(LocalDateTime.now());
                user.setUpdateTime(LocalDateTime.now());
                
                // 插入用户数据
                userMapper.insert(user);
                
                // 缓存用户信息 - 添加null检查
                if (redissonClient != null && user.getId() != null) {
                    redissonClient.getBucket(USER_CACHE_KEY_PREFIX + user.getId()).set(user);
                }
                
                return user;
            } catch (Exception e) {
                logger.error("Error adding user: {}", e.getMessage(), e);
                throw e;
            }
        }).subscribeOn(Schedulers.boundedElastic());
    }
    
    @Override
    public Mono<User> getUserById(Long id) {
        return Mono.fromCallable(() -> {
            if (id == null) {
                logger.error("Attempting to get user with null ID");
                return null;
            }
            
            try {
                // 先从缓存获取 - 添加null检查
                User user = null;
                if (redissonClient != null) {
                    Object cachedUser = redissonClient.getBucket(USER_CACHE_KEY_PREFIX + id).get();
                    if (cachedUser instanceof User) {
                        user = (User) cachedUser;
                    }
                }
                
                if (user != null) {
                    return user;
                }
                
                // 缓存未命中，从数据库获取
                user = userMapper.selectById(id);
                
                // 放入缓存 - 添加null检查
                if (user != null && redissonClient != null) {
                    redissonClient.getBucket(USER_CACHE_KEY_PREFIX + id).set(user);
                }
                return user;
            } catch (Exception e) {
                logger.error("Error getting user by ID {}: {}", id, e.getMessage(), e);
                throw e;
            }
        }).subscribeOn(Schedulers.boundedElastic());
    }
    
    @Override
    public Mono<Boolean> updateUser(User user) {
        return Mono.fromCallable(() -> {
            if (user == null || user.getId() == null) {
                logger.error("Attempting to update null user or user with null ID");
                return false;
            }
            
            try {
                // 设置更新时间
                user.setUpdateTime(LocalDateTime.now());
                
                // 更新数据库
                int rows = userMapper.update(user);
                
                if (rows > 0 && redissonClient != null) {
                    // 更新缓存
                    redissonClient.getBucket(USER_CACHE_KEY_PREFIX + user.getId()).set(user);
                    return true;
                }
                return false;
            } catch (Exception e) {
                logger.error("Error updating user {}: {}", user.getId(), e.getMessage(), e);
                return false;
            }
        }).subscribeOn(Schedulers.boundedElastic());
    }
    
    @Override
    public Mono<Boolean> deleteUser(Long id) {
        return Mono.fromCallable(() -> {
            if (id == null) {
                logger.error("Attempting to delete user with null ID");
                return false;
            }
            
            try {
                // 删除数据库记录
                int rows = userMapper.deleteById(id);
                
                if (rows > 0 && redissonClient != null) {
                    // 删除缓存
                    redissonClient.getBucket(USER_CACHE_KEY_PREFIX + id).delete();
                    return true;
                }
                return false;
            } catch (Exception e) {
                logger.error("Error deleting user {}: {}", id, e.getMessage(), e);
                return false;
            }
        }).subscribeOn(Schedulers.boundedElastic());
    }
}